package com.haohe.wx.services.impl;

import org.apache.log4j.Logger;
import org.dom4j.Element;
import org.springframework.stereotype.Service;

import com.haohe.wx.services.SubscribeService;
import com.haohe.wx.util.DateUtil;
import com.haohe.wx.util.WXUtil;
import com.haohe.wx.wechat.EventType;
import com.haohe.wx.wechat.MsgType;
import com.haohe.wx.wechat.WeChartXml;
import com.haohe.wx.wechat.common.WXBizMsgCrypt;

/**
 * 关注、取消关注事件处理
 * @Title SubscribeServiceImpl.java
 * @author liming.zhao@haohedata.com
 */
@Service("subscribeService")
public class SubscribeServiceImpl implements SubscribeService {

	private static Logger logger = Logger.getLogger(SubscribeServiceImpl.class);
	
	public synchronized String subscribe(String timestamp, String nonce,String reciveMsg) {
		String returnMsg = "";
		try {
			Element element = WXUtil.parseStr2Ele(reciveMsg);
			String event = ((Element) element.selectObject("Event")).getTextTrim();// 企业号CorpID
			if(event.equals(EventType.subscribe.toString())){/**关注企业号时调用*/
				WXBizMsgCrypt pc = new WXBizMsgCrypt();
				String toUserName = ((Element) element.selectObject("ToUserName")).getTextTrim();// 企业号CorpID
				String fromUserName = ((Element) element.selectObject("FromUserName")).getTextTrim();
				String textTpl = String.format(WeChartXml.RECEIVE_TEXT_TPL, toUserName,fromUserName,DateUtil.getCurrentTime(),MsgType.text,"测试成功！！！");
				returnMsg = pc.encryptMsg(textTpl, timestamp, nonce);
			}
		} catch (Throwable t) {
			logger.equals("关注企业号出现异常；异常信息为："+t.getMessage());
			logger.error(t.getMessage());
		}
		
		return returnMsg;
	}

	@Override
	public synchronized String unSubscribe(String timestamp, String nonce,String reciveMsg) {
		return null;
	}

}
